<script setup lang="ts">
import { ref, onMounted } from "vue";
import { useUserStore } from "@/stores/user";
import { useUserAPI } from "@/services/user";
import { useUploadAPI } from "@/services/upload";
import { ElMessage } from "element-plus";

const userStore = useUserStore();
const userAPI = useUserAPI();
const uploadAPI = useUploadAPI();
const username = ref(userStore.username);
const avatar = ref("");
const email = ref("");
const description = ref("");
const previewImage = ref("");
const phone = ref("");
const sex = ref("");
const birthday = ref("");
const fileInputRef = ref<HTMLInputElement | null>(null);

// 组件加载时初始化数据
onMounted(() => {
  username.value = userStore.username;
  email.value = userStore.email || "";
  description.value = userStore.description || "";
  phone.value = userStore.phone || "";
  sex.value = userStore.sex || "男";
  birthday.value = userStore.birthday || "";
});

const handleAvatarChange = (e: Event) => {
  const target = e.target as HTMLInputElement;
  if (target.files && target.files.length > 0) {
    const file = target.files[0];
    // 创建预览URL
    previewImage.value = URL.createObjectURL(file);

    // 调用文件上传接口
    uploadAPI
      .uploadFile(file)
      .then((res: any) => {
        if (res.code === 200) {
          const imageUrl = res.msg;
          userAPI
            .putUpdateAvatar(userStore.uid, imageUrl)
            .then((updateRes: any) => {
              if (updateRes.code === 200) {
                avatar.value = imageUrl;
                // 更新用户store中的头像
                userStore.setAvatar(imageUrl);
                avatar.value = imageUrl;
              }
            });
        }
      })
      .catch((err: any) => {
        console.error("上传文件失败:", err);
      });
  }
};

const triggerFileInput = () => {
  fileInputRef.value?.click();
};

const handleSubmit = async () => {
  try {
    const userInfo = {
      uid: userStore.uid,
      uname: username.value,
      email: email.value,
      phone: phone.value,
      sex: sex.value,
      birthday: birthday.value,
      avatarUrl: userStore.avatarUrl,
      description: description.value,
    };

    const res = await userAPI.postUpdateUserInfo(userInfo);
    if (res.code === 200) {
      // 更新本地store
      userStore.setUserInfo({
        ...userStore.$state,
        username: username.value,
        email: email.value,
        phone: phone.value,
        sex: sex.value,
        birthday: birthday.value,
        description: description.value,
      });
      ElMessage.success("更新成功");
    }
  } catch (error) {
    console.error("更新失败:", error);
    ElMessage.error("更新失败，请重试");
  }
};
</script>

<template>
  <div class="py-8 px-36 relative">
    <h2 class="text-2xl font-semibold mb-8">个人信息设置</h2>
    <el-form
      :model="{ username, email, phone, sex, birthday, description }"
      label-position="top"
      class="max-w-[600px]"
    >
      <el-form-item label="头像">
        <div class="flex items-center space-x-4">
          <img
            :src="previewImage || userStore.avatarUrl"
            class="w-24 h-24 rounded-full object-cover"
            alt="头像预览"
          />
          <div>
            <input
              ref="fileInputRef"
              type="file"
              accept="image/*"
              @change="handleAvatarChange"
              class="hidden"
            />
            <el-button type="primary" @click="triggerFileInput" size="large">
              更换头像
            </el-button>
          </div>
        </div>
      </el-form-item>

      <el-form-item label="用户名">
        <el-input size="large" v-model="username" placeholder="请输入用户名" />
      </el-form-item>

      <el-form-item label="邮箱">
        <el-input
          size="large"
          v-model="email"
          placeholder="请输入邮箱"
          type="email"
        />
      </el-form-item>

      <el-form-item label="手机号">
        <el-input size="large" v-model="phone" placeholder="请输入手机号" />
      </el-form-item>

      <el-form-item label="性别">
        <el-select v-model="sex" size="large" class="w-full">
          <el-option label="男" value="男" />
          <el-option label="女" value="女" />
        </el-select>
      </el-form-item>

      <el-form-item label="生日">
        <el-date-picker
          v-model="birthday"
          type="date"
          size="large"
          class="w-full"
          placeholder="选择生日"
        />
      </el-form-item>

      <el-form-item label="个人简介">
        <el-input
          v-model="description"
          type="textarea"
          :rows="4"
          placeholder="请输入个人简介"
        />
      </el-form-item>

      <el-button
        type="primary"
        size="large"
        @click="handleSubmit"
        class="w-full"
      >
        保存修改
      </el-button>
    </el-form>
  </div>
</template>

<style scoped>
:deep(.el-form-item__label) {
  font-weight: 500;
  color: black;
}
</style>
